/***********************************************************************
 * 	Copyright @ 2011 Zhejiang Yutian Technology Co.,Ltd
 ==================================================================
 Project:        IMSClient
 FileName:       UncaughtException.java
 Describtion:    文件描述
 Author:         xufei
 Create Date:    2014-5-6 下午4:28:04
 *********************************************************************/
package net.hzlj.platform.enterprise.exception;

import net.hzlj.platform.enterprise.BootApp;
import net.hzlj.platform.enterprise.helper.ToastHelper;

/**
 * @ClassName: UncaughtException
 * @Description: 进程中未捕获异常控制
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-7-23 11:15:59
 */
public class UncaughtException implements Thread.UncaughtExceptionHandler {

    private static final String TAG = UncaughtException.class.getSimpleName();

    //CrashHandler实例
    private static UncaughtException instance = new UncaughtException();

    /**
     * 异常句柄
     */
    private Thread.UncaughtExceptionHandler mDefaultHandler;


    public static UncaughtException getInstance(){
        return instance;
    }


    private UncaughtException() {
        //获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        if (!handleException(throwable) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, throwable);
        }
    }


    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false.
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        //使用Toast来显示异常信息
        ToastHelper.newInstance().show(BootApp.getAppContext(), "很抱歉,程序出现异常,即将重启");

        /*Intent intent = BootApp.getAppContext().getPackageManager().getLaunchIntentForPackage(BootApp.getAppContext().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent restartIntent = PendingIntent.getActivity(BootApp.getAppContext(), 0, intent,PendingIntent.FLAG_ONE_SHOT);

        //设置重启,此段代码必须放在退出之前
        AlarmManager mgr = (AlarmManager)BootApp.getAppContext().getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent); // 1秒钟后重启应用
        */
        android.os.Process.killProcess(android.os.Process.myPid());
        return true;
    }

}
